#include "tablemodel.h"

#include <QDir>
#include <QXmlStreamWriter>
TableModel::TableModel()
    :QAbstractTableModel()
{
    localPath = QDir::currentPath() + "/music/musicList.xml";
    loadData();
}

QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if(role != Qt::DisplayRole) return QVariant();
    else if(orientation == Qt::Horizontal){
        if(section <= 2)
            return columnHeaders[section];
        else
            return QVariant();
    }else{
        return tr("%1").arg(section + 1);
    }
}

int TableModel::rowCount(const QModelIndex &parent) const
{
    return musicMsgMap.size();
}

int TableModel::columnCount(const QModelIndex &parent) const
{
    return 3;
}

QVariant TableModel::data(const QModelIndex &index, int role) const
{
    int row = index.row();
    int column = index.column();
    if(row < rowCount()){
        QString key = musicMsgMap.keys().at(row);
        QMap<QString, QString> *musicMsg = musicMsgMap.value(key);
        if(column < columnCount() && !musicMsg->value(columnHeadersSt[column]).isEmpty() && role == Qt::DisplayRole
            )
            return musicMsg->value(columnHeadersSt[column]);
    }
    return QVariant();
}

bool TableModel::removeRows(int row, int count, const QModelIndex &parent)
{
    if(row + count > rowCount()) return false;
    beginRemoveRows(parent, row, row + count - 1);
    int i = 0;
    for(QMap<QString, QMap<QString, QString> *>::iterator it = musicMsgMap.begin() + row; i < count; i++){
        musicMsgMap.remove(it++.key());
    }
    endRemoveRows();
    return true;
}

QModelIndex TableModel::getBackData(QModelIndex &curIndex, PlayType type)
{
    if(type == ROUND){
        if(curIndex.row() - 1 >= 0){
            return index(curIndex.row() - 1, 0);
        }else{
            return index(rowCount() - 1, 0);
        }
    }else{
        return curIndex;
    }
}

QModelIndex TableModel::getNextData(QModelIndex &curIndex, PlayType type)
{
    if(type == ROUND){
        if(curIndex.row() + 1 < rowCount()){
            return index(curIndex.row() + 1, 0);
        }else{
            if(rowCount() == 0) return QModelIndex();
            else return index(0, 0);
        }
    }else{
        return curIndex;
    }
}

QModelIndex TableModel::setMusicMsg(QString fileName, QMap<QString, QString> *musicMsg)
{
    musicMsgMap.insert(fileName, musicMsg);
    for(int i = 0; i < musicMsgMap.keys().count(); i++){
        if(musicMsgMap.keys().at(i) == fileName) {
            beginInsertRows(QModelIndex(), i, i);
            endInsertRows();
            return index(i, 0);
        }
    }
    return QModelIndex();
}

bool TableModel::loadData()
{
    QFile file(localPath);
    if(!file.open(QFile::ReadOnly | QFile::Text)){
        qDebug() << "Open file error, file path: "<<localPath;
        return 1;
    }
    QXmlStreamReader reader(&file);
    qDebug() << "loading history file...";
    while(!reader.atEnd()){
        QXmlStreamReader::TokenType type = reader.readNext();
        if(type == QXmlStreamReader::StartElement && reader.name().toString() == "播放记录") continue;
        if(type == QXmlStreamReader::StartElement){
            qDebug() << reader.name();
            QString fileName;
            QMap<QString, QString> *musicMsg = new QMap<QString, QString>();
            if(reader.attributes().hasAttribute("path")){
                fileName = reader.attributes().value("path").toString();
            }
            for (int i = 0; i < 3; i++) {
                if(reader.attributes().hasAttribute(columnHeadersSt[i])){
                    musicMsg->insert(columnHeadersSt[i], reader.attributes().value(columnHeadersSt[i]).toString());
                }
            }
            if(!fileName.isEmpty()) setMusicMsg(fileName, musicMsg);
        }
    }
    qDebug() << "history file loaded...";
    return 0;
}

bool TableModel::saveData()
{
    QFile file(localPath);
    if(!file.open(QFile::WriteOnly | QFile::Text)){
        qDebug() << "Open file error, file path: "<<localPath;
        return 1;
    }
    QXmlStreamWriter out(&file);
    out.setAutoFormatting(true);
    qDebug() << "savinging history file to" << localPath;
    out.writeStartDocument();
    out.writeStartElement("播放记录");
    int count = 1;
    foreach (QString key, musicMsgMap.keys()) {
        out.writeStartElement(tr("记录%1").arg(count++));
        out.writeAttribute("path", key);
        for(int i = 0; i < 3; i++) {
            out.writeAttribute(columnHeadersSt[i], musicMsgMap.value(key)->value(columnHeadersSt[i]));
        }
        out.writeEndElement();
    }
    out.writeEndElement();
    out.writeEndDocument();
    file.close();
    qDebug() << "history file saved...";
    return 0;
}

QString TableModel::getFileNameByIndex(const QModelIndex &index)
{
    int row = index.row();
    if(row < rowCount()) return musicMsgMap.keys().at(row);
    else return nullptr;
}


QModelIndex TableModel::getIndexByFileName(const QString fileName)
{
    for(int i = 0; i < musicMsgMap.keys().count(); i++){
        if(musicMsgMap.keys().at(i) == fileName) {
            return index(i, 0);
        }
    }
    return QModelIndex();
}


